package core

import "container/heap"
import "github.com/shopspring/decimal"

type OrderType int

const (
	BuyOrder OrderType = iota
	SellOrder
)

type Order struct {
	ID     uint64
	Uid    int64
	Price  decimal.Decimal
	Amount decimal.Decimal
	Time   int64
}

type OrderList struct {
	OrderType OrderType
	Data      []*Order
}

func NewOrderList(typ OrderType) *OrderList {
	o := &OrderList{
		OrderType: typ,
		Data:      make([]*Order, 0),
	}
	heap.Init(o)
	return o
}

func (c *OrderList) Len() int {
	return len(c.Data)
}

func (c *OrderList) Swap(i, j int) {
	c.Data[i], c.Data[j] = c.Data[j], c.Data[i]
}

func (c *OrderList) Less(i, j int) bool {
	if c.OrderType == BuyOrder {
		if c.Data[i].Price.Equal(c.Data[j].Price) {
			return c.Data[i].Time < c.Data[j].Time
		} else {
			return c.Data[i].Price.GreaterThan(c.Data[j].Price)
		}
	} else {
		if c.Data[i].Price.Equal(c.Data[j].Price) {
			return c.Data[i].Time < c.Data[j].Time
		} else {
			return c.Data[i].Price.LessThan(c.Data[j].Price)
		}
	}
}

func (c *OrderList) Push(x interface{}) {
	v := x.(*Order)
	c.Data = append(c.Data, v)
}

func (c *OrderList) Pop() interface{} {
	var n = c.Len()
	var item = c.Data[n-1]
	c.Data = c.Data[0 : n-1]
	return item
}
